package cn.net.isir.dao;

import cn.net.isir.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Repository
@SuppressWarnings("all")
public class MinipIndexDataDao {
    @Resource
    protected SqlSessionTemplate sqlSessionTemplate;

    @Resource
    private UserValidInfoDao userValidInfoDao;
    @Resource
    private TurnShopDao turnShopDao;
    @Resource
    private MessageDao messageDao;
    @Resource
    private ShopDao shopDao;


    protected String getNamespace() {
        return MinipIndexDataDao.class.getName();
    }

    /**
     * 获取当前最新通知
     *
     * @return
     */
    public Message msgTitel() {
        Message msgTitle = sqlSessionTemplate.selectOne(getNamespace() + ".selectOneMsgTitle");
        return msgTitle;
    }

    /**
     * 查询当月流水
     *
     * @param salesmanId 销售人员ID
     * @return 当月流水数字
     */
    public BigDecimal queryMonthFlow(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);//转出商家Id
        map.put("timeRangeList", timeRangeList);//有效范围
        BigDecimal monthFlow = sqlSessionTemplate.selectOne(getNamespace() + ".queryMonthFlow", map);
//        Map<String, BigDecimal> result2 = sqlSessionTemplate.selectOne(getNamespace() + ".queryMonthFlow", map);
//        BigDecimal monthFlow = result2.get("total");
        return monthFlow;
    }

    /**
     * 查询时间段内的流水
     *
     * @param salesman  销售人员ID
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 总流水
     */
    public BigDecimal queryIntervalFlow(Map<String, List<TimeRange>> salesman, String turnedShopIds, Date startTime, Date endTime) {
        BigDecimal total = BigDecimal.ZERO;//设置总流水为0
        Map<String, Object> map = new HashMap<>();
        // 循环每个人员
        for (Map.Entry<String, List<TimeRange>> stringListEntry : salesman.entrySet()) {
            String key = stringListEntry.getKey();
            List<TimeRange> value = stringListEntry.getValue();
            map.clear();
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("salesmanId", key);
            map.put("turnedShpIds", turnedShopIds);
            map.put("timeRangeList", value);
            BigDecimal intervalFlow = sqlSessionTemplate.selectOne(getNamespace() + ".queryIntervalFlow", map);
            if (intervalFlow != null) {
                total = total.add(intervalFlow);
            }
        }
        return total;
    }

    /**
     * 查询某店铺，时间段内的总流水
     *
     * @param timeRangeList 时间段列表
     * @param shopId        店铺id
     * @param startTime     开始时间
     * @param endTime       结束时间
     * @return 总流水
     */
    public BigDecimal queryShopIntervalFlow(List<TimeRange> timeRangeList, String shopId, Date startTime, Date endTime) {
        BigDecimal total = BigDecimal.ZERO;
        Map<String, BigDecimal> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("shopId", shopId);
        map.put("timeRangeList", timeRangeList);
        Map<String, BigDecimal> result2 = sqlSessionTemplate.selectOne(getNamespace() + ".queryShopIntervalFlow", map);
        BigDecimal intervalFlow = result2.get("total");
        return intervalFlow;
    }

    /**
     * 查询当日流水
     *
     * @param salesmanId 销售人员ID
     * @return 当日流水数字：dayFlow，dayOrderCount
     */
    public Map queryDayFlow(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        Map map2 = sqlSessionTemplate.selectOne(getNamespace() + ".queryDayFlow", map);
        return map2;
    }

    /**
     * 根据销售人员Id查询店铺当日流水
     *
     * @param salesmanId    销售人员ID
     * @param turnedShopIds 已转出店铺列表
     * @param timeRangeList 销售人员有效范围列表
     * @return 店
     */
    public List<Map<String, Object>> queryShopDayFlow(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Shop> shops = noTurnShopList(salesmanId, turnedShopIds);

        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("salesmanId", salesmanId);
        params.put("turnedShpIds", turnedShopIds);
        params.put("timeRangeList", timeRangeList);

        Map<String, Object> map = null;
        for (Shop shop : shops) {
            params.put("shopId", shop.getId());
            Map shopInfo = sqlSessionTemplate.selectOne(getNamespace() + ".queryShopDayFlow", params);//dayAmount,dayOrderNum,shopId
            list.add(shopInfo);
        }
        return list;
    }

    /**
     * 查询本月未结转店铺数
     *
     * @param salesmanId 销售人员ID
     * @return 本月可结转店铺数
     */
    public int noTurnedShop(String salesmanId, String turnedShopIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        List<Shop> shopList = sqlSessionTemplate.selectList(getNamespace() + ".noTurnShopCount", map);
        return shopList.size();
    }


    /**
     * 获取本月未结转店铺列表
     *
     * @param salesmanId
     * @param turnedShpIds
     * @return
     */
    public List<Shop> noTurnShopList(String salesmanId, String turnedShopIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);

        List<Shop> shops = sqlSessionTemplate.selectList(getNamespace() + ".noTurnShopList", map);
        return shops;
    }

    /**
     * 可结转数
     *
     * @param salesmanId 销售人员ID
     * @return 达标数量
     */
    public int monthCanTurnShops(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId",salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        List<Shop> shopList = sqlSessionTemplate.selectList(getNamespace() + ".CanTurnShops", map);
        return shopList.size() == 0 ? 0 : shopList.size();


       /* Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        List<Shop> shopList = new ArrayList<>();
        for (int i=1; i<=day; i++){
            String startTime = getDayListOfMonth("00:00:00",i);
            String endTime = getDayListOfMonth("23:59:59",i);

            map.put("startTime",startTime);
            map.put("endTime",endTime);
            Shop shop = sqlSessionTemplate.selectOne(getNamespace() + ".dayLiveNum", map);
            shopList.add(shop);
        }
        int num = 0;
        for (int j=0; j<shopList.size()-1; j++){
            if(shopList.get(j).getId().equals(shopList.get(j+1).getId())){
                ++num;
            }
        }*/
    }

    /**
     * 今天日活达标数
     *
     * @param salesmanId 销售人员ID
     * @return 达标数量
     */
    public int dayLiveCount(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        List<Map> list = sqlSessionTemplate.selectList(getNamespace() + ".dayLive", map);
        return list == null ? 0 : list.size();
    }

    /**
     * 今天日活未达标数
     *
     * @param salesmanId 销售人员ID
     * @return 日货未达标店铺数
     */
    public int dayNotLiveCount(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        List<Map> shopList = sqlSessionTemplate.selectList(getNamespace()+".dayNotLiveNotOrder",map);
        List<Map> list = sqlSessionTemplate.selectList(getNamespace() + ".dayNotLive", map);
        list.addAll(shopList);
        return list == null ? 0 : list.size();
    }

    /**
     * 日活未达标店铺列表
     *
     * @param salesmanId 销售人员ID
     * @return 日活未达标店铺列表
     */
    public List<Map<String,Object>> getDayNoLiveShopList(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        List<Map<String,Object>> list = new ArrayList<>();

        //获取日活未达标店铺List
        Map<String, Object> map1 = new HashMap<>();
        map1.put("salesmanId", salesmanId);
        map1.put("turnedShpIds", turnedShopIds);
        map1.put("timeRangeList", timeRangeList);
        //日活未达标店铺：今日没有订单
        List<Shop> shopList = sqlSessionTemplate.selectList(getNamespace() + ".dayNotLiveNotOrder", map1);
        //日活未达标店铺：今日有订单，但不符合达标标准
        List<Shop> shops = sqlSessionTemplate.selectList(getNamespace() + ".dayNotLive", map1);
        shops.addAll(shopList);
        //根据日活未达标店铺shopId查询对应的订单和流水信息
        Map<String, Object> map2 = null;
        for (Shop shop : shops) {
            map2 = new HashMap<>();
            map2.put("shopId", shop.getId());
            map2.put("salesmanId", salesmanId);
            map2.put("turnedShpIds", turnedShopIds);
            map2.put("timeRangeList", timeRangeList);
            Map<String,Object> m = sqlSessionTemplate.selectOne(getNamespace() + ".queryShopDayFlow", map2);
            Shop shop1 = sqlSessionTemplate.selectOne(getNamespace() + ".shopInfo", map2);
            m.put("shopName", shop1.getName());
            m.put("createTime", shop1.getCreateTime());
            m.remove("shopId");
           /* map.put("shopName", shop1.getName());
            map.put("createTime", shop1.getCreateTime());
            map.put("dayOrderNum",m.get("dayOrderNum"));
            map.put("dayAmount",m.get("dayAmount"));*/
            list.add(m);
        }
        return list;
    }

    /**
     * 查询销售人员中，尚未转出店铺的列表
     *
     * @param salesmanIds  销售人员列表
     * @param turnedShpIds 已转出店铺列表
     * @return 店铺列表
     */
    public PageInfo<Shop> queryHasNotTurnedShop(String salesmanIds, String name, String turnedShpIds, Integer pageNo, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanIds", salesmanIds);
        map.put("turnedShpIds", turnedShpIds);
        map.put("name",name);
        // 支持分页
        if (pageNo == null || pageSize == null) {
            pageNo = 1;
            pageSize = 0;
        }
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(sqlSessionTemplate.selectList(getNamespace() + ".hasNotTurnShops", map));
    }

    /**
     * 获取已转出店铺列表
     *
     * @return 转出店铺的ID列表(逗号分隔)
     */
    public String turnedShopIds() {

        StringBuilder turnShopIds = new StringBuilder();
        //转出店铺
        List<TurnShop> turnShopList = turnShopDao.selectList(null);
        turnShopList.forEach(item -> turnShopIds.append(item.getShopId()).append(","));
//        Collection<String> turnShops = (Collection) turnShopDao.selectList(null);
        return turnShopIds.substring(0, turnShopIds.length() - 1);
    }

    /**
     * 获取销售人员有效期时间段列表
     *
     * @param salesmanId 销售人员ID
     * @return 有效时间列表
     */
    public List<TimeRange> getTimeRangeList(String salesmanId) {
        List<TimeRange> timeRangeList = new ArrayList<>();
        UserValidInfo userValidInfo = new UserValidInfo();
        userValidInfo.setUserId(salesmanId);
        List<UserValidInfo> list = userValidInfoDao.selectList(userValidInfo);
        // 是否已经开始
        boolean isStarted = false;

        TimeRange timeRange = null;

        // 增加记录
        for (UserValidInfo validInfo : list) {
            if (validInfo.getChangeStatus() == 1) {
                isStarted = true;
            }
            if (isStarted) {
                if (validInfo.getChangeStatus() == 1) {
                    // 防止两次连续设置为有效
                    if (timeRange == null) {
                        timeRange = new TimeRange();
                    }
                    timeRange.setStartTime(validInfo.getChangeTime());
                }
                //增加timeRange判断，防止代码报错，并且防止两次连续设置为null
                if (timeRange != null && validInfo.getChangeStatus() == 0) {
                    timeRange.setEndTime(validInfo.getChangeTime());
                    timeRangeList.add(timeRange);
                    timeRange = null;
                }
            }
        }
        return timeRangeList;
    }

    /**
     * 通知列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<Message> queryMsgList(Integer pageNo, Integer pageSize) {
        // 支持分页
        if (pageNo == null || pageSize == null) {
            pageNo = 1;
            pageSize = 10;
        }
        Message message = new Message();
        message.setIsPublished(1);
        return messageDao.selectPageList(message, pageNo, pageSize);
    }

    /**
     * 根据消息id获取消息详情
     *
     * @param id
     * @return
     */
    public Message findMsgInfo(String id) {
        return messageDao.selectByPrimaryKey(id);
    }

    /**
     * 获取每一天的数据
     * @param shopId 店铺id
     * @param salesmanId 销售人员Id
     * @param turnedShopIds 已转出店铺id
     * @param timeRangeList 销售人员有效时间段
     * @return 每天的列表
     */
    public List<Map> queryEveryDayFlow(String shopId, String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList) {
        Map map = new HashMap<>();
        map.put("shopId", shopId);
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        List<Map> everyDay = sqlSessionTemplate.selectList(getNamespace() + ".queryEveryDayFlow", map);
        return everyDay;
    }

    /**
     * 结转记录
     *
     * @param salesmanId
     * @return
     */
    public List<Map<String, Object>> getTurnHistoryList(String salesmanId) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        //获取转出店铺详细信息
        List<Map<String, Object>> turnShopList = sqlSessionTemplate.selectList(getNamespace() + ".queryTurnedShop", map);
        return turnShopList;
    }

    private String getDayListOfMonth(String hms, int i) {
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        String aDate = "";
        int year = aCalendar.get(Calendar.YEAR);//年份
        int month = aCalendar.get(Calendar.MONTH) + 1;//月份
        int day1 = aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        if(i<10){
            String day = "0"+i;
            aDate = String.valueOf(year)+"-"+month+"-"+day+" "+hms;
        }else{
            aDate = String.valueOf(year)+"-"+month+"-"+i+" "+hms;
        }
        return aDate;
    }
}
